package com.example.admin_test.controller;

import com.example.admin_test.common.vo.Result;
import com.example.admin_test.pojo.User;
import com.example.admin_test.service.Impl.UserServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserServiceImpl userService;
    @RequestMapping("/")
    public String print(){
        System.out.println("输出OK");
        return "ress";
    }
    @PostMapping("/login")
    public Result login(User user, @RequestParam("captcha")String captcha , HttpServletRequest request, HttpSession session, Model model){
        Result result = new Result();
        if (!CaptchaUtil.ver(captcha, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return result.fail("验证码不正确");
        }
        User login = userService.login(user);
        session.setAttribute("userInfo",user);
        if(login!=null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(user.getPassword(), login.getPassword());
            if(matches){
                login.setPassword(null);
                return result.success(login);
            }
        }
        return result.fail("账号或者密码错误");
    }
}
